#ifndef __input
#define __input

#include <utils.h>

struct keyboard {

	private:

		int nkeys; // number of keys

		Uint8* now; // key state now (1 - down, 0 - up)
		Uint8* last; // last key state

		// for key repeat
		clock_t* tstamp; // time stamp when key is first down
		clock_t* repeat; // time for key to repeat

	public:
		keyboard () {
			SDL_GetKeyState (&nkeys);
			last = new Uint8 [nkeys];
			tstamp = new clock_t [nkeys];
			repeat = new clock_t [nkeys];
		}
		~keyboard () {
			delete [] last;
			delete [] tstamp;
			delete [] repeat;
		}
		void read () { // current keyboard state
			now = SDL_GetKeyState (0);
		}

	friend int keydown (unsigned int k);
	friend int waskeydown (unsigned int k);
	friend int keypressed (unsigned int k);
	friend int keypressedd (unsigned int k, clock_t first_t, clock_t const_t);
	friend int nkeys ();

};

keyboard keybd;

inline void read_keybd () {
	keybd.read ();
}

inline int keydown (unsigned int k) {
	int r = keybd.now[k];
	keybd.last[k] = r;
	return r;
}

inline int waskeydown (unsigned int k) {
	return keybd.last[k];
}

inline int keypressed (unsigned int k) {
	int wkd = waskeydown (k), kd = keydown (k);
	if (kd && !wkd) return true; else return false;
}

inline int keypressedd (unsigned int k, clock_t first_t=secs2ticks(1./4), clock_t const_t=secs2ticks(1./64)) {

	/* keypressed with key repeat */

	int wkd = waskeydown(k), kd = keydown(k);
	if (kd) {
		if (!wkd) {
			keybd.tstamp[k] = clock();
			keybd.repeat[k] = first_t;
			return true;
		} else {
			clock_t t = clock();
			clock_t dt = t - keybd.tstamp[k];
			if (dt > keybd.repeat[k]) {
				keybd.tstamp[k] = t;
				keybd.repeat[k] = const_t;
				return true;
			}
		}
	}
	return false;
}

inline int nkeys () {
	return keybd.nkeys;
}

int mousex, mousey;

inline void read_mouse () {
	SDL_GetMouseState (&mousex, &mousey);
}
#endif
